import config from '@/config/index.js'
import {
	getToken
} from '@/utils/token.js'
import {
	useUserStore
} from '@/store/index.js'

const serverUrl = config.serverUrl[process.env.NODE_ENV]

let isRefreshToken = false;
let requestList = [];

const request = (method, url, data) => {
	return new Promise((resolve, rejict) => {
		uni.request({
			url: serverUrl + url,
			data,
			header: {
				Authorization: `Bearer ${getToken()}`,
				'tenant-id': '1'
			},
			method,
			success: (res) => {
				res = res.data
				if (res.code === 401) {
					if (!isRefreshToken) {
						isRefreshToken = true;
						const userStore = useUserStore();
						userStore.refreshToken().then(() => {
							requestList.forEach((cb) => cb());
							requestList = [];
						}).catch(error => {
							userStore.logout()
							uni.reLaunch({
								url: '/pages/index/index'
							})
						}).finally(() => {
							isRefreshToken = false;
						})
					}
					requestList.push(() => {
						resolve(request(method, url, data));
					});
					return
				}
				if (res.code === 0) {
					resolve(res.data)
				} else {
					rejict(res.msg)
				}
			},
			fail: () => {
				rejict('Request Error')
			},
		});
	})
}

export default {
	get: (url, data) => request('GET', url, data),
	post: (url, data) => request('POST', url, data),
	put: (url, data) => request('PUT', url, data),
	delete: (url, data) => request('DELETE', url, data)
}